package logic

import (
	"context"
	"errors"
	"user-item/models/cache"
	"user-item/models/mysql"
	"user-item/pkg"

	"user-item/userrpc/internal/svc"
	"user-item/userrpc/userrpc"

	errors2 "github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *userrpc.UpdatePasswordRequest) (*userrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, errors2.New("用户不存在")
	}
	if user.Password != pkg.Md5(in.OldPassword) {
		return nil, errors.New("原密码输入错误")
	}
	if in.NewPassword != in.AckNewPassword {
		return nil, errors.New("两次密码输入不一致")
	}
	if in.OldPassword == in.NewPassword {
		return nil, errors.New("新密码和原密码输入一致，不允许修改")
	}
	result2, _ := cache.Rdb.Get(l.ctx, "sendSms"+user.Phone).Result()
	if result2 != in.SendSmsCode {
		return nil, errors.New("短信验证码错误")
	}
	user.Password = pkg.Md5(in.NewPassword)
	err := user.UserUpdate(mysql.DB)
	if err != nil {
		return nil, errors.New("密码修改失败")
	}

	return &userrpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
